

const theKeyNameList = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

function nop() { }

function makeKey(groupNum, keyNum) {
    const down = false;
    const keyMax = 127
    let code = (groupNum * 12) + keyNum;
    if (code > keyMax) {
        return null;
    }
    let name = theKeyNameList[keyNum]
    let label = name + '(' + code + ')'
    let id = name + groupNum
    let velocity = 0
    return { code, name, id, label, down, velocity }
}

function initKeys() {
    let list = []
    let more = true;
    for (var group = 0; more; group++) {
        for (var key = 0; key < 12; key++) {
            let item = makeKey(group, key)
            if (item == null) {
                more = false
                break
            }
            list.push(item)
        }
    }
    return list
}

const theKeys = initKeys()

////////////////////////////////////////////////////////////////////////////////

const state = {
    keys: theKeys // as a array[]
};

const mutations = {

    keyDown(state, key_table) {
        let all = state.keys;
        for (var k in key_table) {
            let v = key_table[k]
            let key = all[k];
            if (key == null) { continue }
            key.down = true
            key.velocity = v
        }
    },

    keyUp(state, key_table) {
        let all = state.keys;
        for (var k in key_table) {
            let v = key_table[k]
            let key = all[k];
            if (key == null) { continue }
            key.down = false
            key.velocity = 0
            nop(v)
        }
    },

    reset(state) {
        let all = state.keys;
        for (var i in all) {
            let item = all[i]
            item.down = false
            item.velocity = 0
        }
    },

};

const actions = {
    xxx(context) {
        nop(context)
    }
};

const getters = {
    keys(state) {
        return state.keys
    }
};

export default {
    name: "keyboard",
    namespaced: true,
    state, mutations, actions, getters
}
